import { useRef, useState } from 'react';
import { ReloadOutlined, SettingOutlined, PlusOutlined } from '@ant-design/icons';
import type { ActionType } from '@ant-design/pro-components';
import {
  operationAlarmContactListApi,
  operationAlarmContactSaveApi,
  operationAlarmContactDeleteApi,
} from '@/api/operationAlarmApi';
import type { BizAlarmContact } from '@/api/operationAlarmApi';
import { TableLocalePresets } from '@/utils/tableUtils';

const AlarmContactList = () => {
  const actionRef = useRef<ActionType>(null);
  const [form] = AForm.useForm();
  const [drawerVisible, setDrawerVisible] = useState(false);
  const [drawerTitle, setDrawerTitle] = useState('新增联系人');
  const [currentRecord, setCurrentRecord] = useState<BizAlarmContact | null>(null);
  const [drawerType, setDrawerType] = useState<'add' | 'edit'>('add');

  // 获取联系人列表
  const fetchContactList = async (params: any) => {
    try {
      const res = await operationAlarmContactListApi({
        pageNum: params.current,
        pageSize: params.pageSize,
        ...params,
      });

      if (res.success) {
        return {
          success: true,
          data: res.data || [],
          total: res.data.length || 0,
        };
      } else {
        window.$message.error(res.message || '获取联系人列表失败');
        return {
          success: false,
          data: [],
          total: 0,
        };
      }
    } catch (error) {
      console.error('获取联系人列表失败:', error);
      window.$message.error('获取联系人列表失败');
      return {
        success: false,
        data: [],
        total: 0,
      };
    }
  };

  // 保存联系人（新增或编辑）
  const saveContact = async () => {
    try {
      const values = await form.validateFields();
      const params = {
        ...values,
        id: drawerType === 'edit' ? currentRecord?.id : undefined,
      };

      const res = await operationAlarmContactSaveApi(params);

      if (res.success) {
        window.$message.success(drawerType === 'add' ? '新增成功' : '编辑成功');
        setDrawerVisible(false);
        form.resetFields();
        setCurrentRecord(null);
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || (drawerType === 'add' ? '新增失败' : '编辑失败'));
      }
    } catch (error) {
      console.error('保存联系人失败:', error);
      window.$message.error(drawerType === 'add' ? '新增失败' : '编辑失败');
    }
  };

  // 删除联系人
  const deleteContact = async (record: BizAlarmContact) => {
    if (!record.id) return;

    try {
      const res = await operationAlarmContactDeleteApi({ id: String(record.id) });

      if (res.success) {
        window.$message.success('删除成功');
        actionRef.current?.reload();
      } else {
        window.$message.error(res.message || '删除失败');
      }
    } catch (error) {
      console.error('删除联系人失败:', error);
      window.$message.error('删除失败');
    }
  };

  // 显示新增抽屉
  const showAddDrawer = () => {
    setDrawerType('add');
    setDrawerTitle('新增联系人');
    setCurrentRecord(null);
    form.resetFields();
    setDrawerVisible(true);
  };

  // 显示编辑抽屉
  const showEditDrawer = (record: BizAlarmContact) => {
    setDrawerType('edit');
    setDrawerTitle('编辑联系人');
    setCurrentRecord(record);
    form.setFieldsValue(record);
    setDrawerVisible(true);
  };

  const columns = [
    {
      title: '姓名',
      dataIndex: 'name',
      key: 'name',
      width: 120,
      search: true,
    },
    {
      title: '组织',
      dataIndex: 'orgName',
      key: 'orgName',
      width: 150,
      search: true,
    },
    {
      title: '电话',
      dataIndex: 'phone',
      key: 'phone',
      width: 120,
      search: true,
    },
    {
      title: '邮箱',
      dataIndex: 'email',
      key: 'email',
      width: 150,
      search: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      key: 'remark',
      width: 150,
      search: false,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      key: 'createTime',
      width: 180,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 150,
      fixed: 'right',
      search: false,
      render: (_: any, record: BizAlarmContact) => (
        <ASpace size="small">
          <AButton type="link" size="small" onClick={() => showEditDrawer(record)}>
            编辑
          </AButton>
          <APopconfirm
            title="确认删除?"
            description="确认要删除该联系人吗？"
            onConfirm={() => deleteContact(record)}
            okText="确认"
            cancelText="取消"
          >
            <AButton type="link" size="small" danger>
              删除
            </AButton>
          </APopconfirm>
        </ASpace>
      ),
    },
  ];

  return (
    <div className="w-full">
      <PProTable<BizAlarmContact>
        className="mh-table"
        actionRef={actionRef}
        columns={columns}
        request={fetchContactList}
        rowKey="id"
        search={{
          span: 6,
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={false}
        // pagination={{
        //   defaultPageSize: 100000,
        //   showSizeChanger: false,
        //   showQuickJumper: true,
        //   showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
        // }}
        scroll={{ x: 1000 }}
        size="small"
        options={{
          density: false,
          reloadIcon: (
            <AButton icon={<ReloadOutlined />} key="reload">
              刷新
            </AButton>
          ),
          setting: {
            draggable: true,
            checkable: true,
            showListItemOption: true,
            settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
            listsHeight: 400,
          },
        }}
        locale={TableLocalePresets.product(actionRef)}
        toolBarRender={() => [
          <AButton key="add" type="primary" icon={<PlusOutlined />} onClick={showAddDrawer}>
            新增联系人
          </AButton>,
        ]}
      />

      {/* 联系人抽屉 */}
      <ADrawer
        title={drawerTitle}
        width={600}
        open={drawerVisible}
        onClose={() => {
          setDrawerVisible(false);
          form.resetFields();
          setCurrentRecord(null);
        }}
        footer={
          <div className="flex justify-end">
            <AButton
              onClick={() => {
                setDrawerVisible(false);
                form.resetFields();
                setCurrentRecord(null);
              }}
              className="mr-2"
            >
              返回
            </AButton>
            <AButton type="primary" onClick={saveContact}>
              保存
            </AButton>
          </div>
        }
      >
        <AForm form={form} layout="vertical" labelAlign="right" labelCol={{ span: 12 }}>
          <AForm.Item label="姓名" name="name" rules={[{ required: true, message: '请输入姓名!' }]}>
            <AInput placeholder="请输入姓名" />
          </AForm.Item>

          <AForm.Item
            label="组织"
            name="orgName"
            rules={[{ required: true, message: '请输入组织!' }]}
          >
            <AInput placeholder="请输入组织" />
          </AForm.Item>

          <AForm.Item
            label="电话"
            name="phone"
            rules={[
              { required: true, message: '请输入电话!' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码!' },
            ]}
          >
            <AInput placeholder="请输入电话" />
          </AForm.Item>

          <AForm.Item
            label="邮箱"
            name="email"
            rules={[
              { required: true, message: '请输入邮箱!' },
              { type: 'email', message: '请输入正确的邮箱地址!' },
            ]}
          >
            <AInput placeholder="请输入邮箱" />
          </AForm.Item>

          <AForm.Item label="备注" name="remark">
            <AInput.TextArea rows={4} placeholder="请输入备注" />
          </AForm.Item>
        </AForm>
      </ADrawer>
    </div>
  );
};

export default AlarmContactList;
